import {
  renameFriendUsingPost,
} from "@/api/userRelationshipController";
import type { ProFormInstance } from "@ant-design/pro-components";
import { ProForm, ProFormText } from "@ant-design/pro-components";
import { Form, message, Modal } from "antd";
import React, { useRef, useEffect } from "react";
import loginUser from "@/stores/loginUser";
import {RootState} from "@/stores";
import { useSelector } from "react-redux";
interface Props {
  oldData?: API.FunRiceUserRelationshipAddthumb;
  visible: boolean;
  onSubmit: () => void;
  onCancel: () => void;
}

/**
 * 更新好友备注的模态框
 */

const UpdateModal: React.FC<Props> = (props) => {
  const { visible, oldData, onSubmit, onCancel } = props;
  const [form] = Form.useForm();
  const formRef = useRef<ProFormInstance>();

  useEffect(() => {
    if (oldData) {
      form.setFieldsValue({
        bfriendsNameRemarks: oldData.bfriendsNameRemarks
      });
    }
  }, [oldData]);
  /**
   * 提交表单
   */
  const loginUser = useSelector((state: RootState) => state.loginUser);

  const handleSubmit = async () => {
    const values = await form.validateFields();
    if (!oldData?.userAccount && !oldData?.friendsUserAccount) {
      message.error("用户饭点号不能为空");
      return;
    }

    const currentUserAccount = loginUser.userAccount;
    if (currentUserAccount!==oldData.friendsUserAccount&&currentUserAccount!==oldData.userAccount) {
      message.error("您们还不是好友");
      return false;
    }
    const targetAccount = oldData.userAccount === currentUserAccount
        ? oldData.friendsUserAccount
        : oldData.userAccount;

    const hide = message.loading("正在更新");

    try {
      await renameFriendUsingPost({
        userAccount: targetAccount,
        bfriendsNameRemarks: values.bfriendsNameRemarks,
      });
      hide();
      message.success("更新成功");
      onSubmit?.();
    } catch (error: any) {
      hide();
      message.error(error.message);
    }
  };

  return (
    <Modal
      title="修改好友备注"
      open={visible}
      onOk={handleSubmit}
      onCancel={onCancel}
      okText="提交"
      cancelText="取消"
    >
      <ProForm
        form={form}
        formRef={formRef}
        submitter={false}
        initialValues={oldData}
      >
        <ProFormText
          name="bfriendsNameRemarks"
          label="备注"
          placeholder="请输入备注"
          rules={[{ required: true, message: "请输入备注" }]}
        />
      </ProForm>
    </Modal>
  );
};

export default UpdateModal;
